package com.xuecheng.content.service;

import cn.hutool.core.io.IoUtil;
import com.xuecheng.content.config.MinioTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @author HuangYuwu
 * @CreateTime 2022/9/14 20:09
 */
@Service
public class PubPageService {
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private Configuration configuration;
    @Async
    public void uploadHtml(Map map, Long courseBaseId) throws IOException, TemplateException {
        Template template = configuration.getTemplate("learing_article.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(html.getBytes());

        minioTemplate.uploadHtml(byteArrayInputStream, courseBaseId + ".html");
    }


    @Async
    public void deleteHtml(Long courseId) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioTemplate.deleteHtml("pages/" +courseId+".html");
    }
}
